package cn.linran.org.service.impl;

import cn.linran.basic.query.BaseQuery;
import cn.linran.basic.service.impl.BaseServiceImpl;
import cn.linran.basic.util.PageList;
import cn.linran.org.domain.Department;
import cn.linran.org.mapper.DepartmentMapper;
import cn.linran.org.query.DepartmentQuery;
import cn.linran.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 保存部门
     * @param department
     */
    @Transactional
    @Override
    public void save(Department department) {
        //调用一次save，返回自增的主键id
        departmentMapper.save(department);
        if(department.getParent_id()==null){
            Long id = department.getId();
            department.setDirPath("/"+id);
        }else{

            String parentPath = departmentMapper.loadById(department.getParent_id()).getDirPath();//得到父级部门的dirPath
            department.setDirPath(parentPath+"/"+department.getId());
        }
        update(department);//将改完dirPath的对象更新到数据库

    }

    @Transactional
    @Override
    public void update(Department department) {
        departmentMapper.save(department);
    }


    @Override
    public List<Department> deptTree() {
        //1.一次性查出所有数据，放到map中
        List<Department> all = departmentMapper.loadAll();
        Map<Long,Department> map = new HashMap<>();
        for(Department department:all){
            map.put(department.getId(),department);
        }
        //2、从所有数据中找出顶级部门(这就是我们需要返回的数据)
        ArrayList<Department> deptTree = new ArrayList<>();
        for(Department department:all){
            if(department.getParent_id()==null){
                deptTree.add(department);//将顶级部门加入deptTree
            }else{
                Long parent_id = department.getParent_id();//如果此部门不是顶级部门，存储其父部门id
                Department parentDepartment = map.get(parent_id);//得到父部门对象
                parentDepartment.getChildren().add(department);//将部门加入到父部门的儿子集合
            }
        }
        return deptTree;
    }

}
